package com.itzh.netty.codec2;

import com.itzh.netty.codec.StudentPOJO;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        MyDataInfo.MyMessage myMessage = (MyDataInfo.MyMessage) msg;
        MyDataInfo.MyMessage.DataType dataType = ((MyDataInfo.MyMessage) msg).getDataType();
        if(dataType == MyDataInfo.MyMessage.DataType.StudentType){
            System.out.println("学生Id="+myMessage.getStudent().getId()+",学生姓名="+myMessage.getStudent().getName());
        }else if(dataType == MyDataInfo.MyMessage.DataType.WorkerType){
            System.out.println("工人名字="+myMessage.getWorker().getName()+",工人Id="+myMessage.getWorker().getAge());
        }else{
            System.out.println("传输的类型不正确");
        }


//        ctx.channel().eventLoop().execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(1000*10);
//                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端2~",CharsetUtil.UTF_8));
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        ctx.channel().eventLoop().schedule(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(1000*5);
//                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端3~",CharsetUtil.UTF_8));
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        },5, TimeUnit.SECONDS);
//        System.out.println("go on ....");


        //        System.out.println("server ctx = "+ctx);
//        //ByteBuf 是 Netty提供的
//        ByteBuf buf = (ByteBuf) msg;
//        System.out.println("客户端发送消息是："+buf.toString(CharsetUtil.UTF_8));
//        System.out.println("客户端地址："+ctx.channel().remoteAddress());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~1",CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
